package com.company.example.concurrent.cyclicBarrier;

import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by ywl on 2017/2/20.
 */
public class BankWateService implements Runnable{
    /**
     * 创建4个屏障，处理完之后执行当前类的run方法
     */
    private CyclicBarrier c = new CyclicBarrier(4,this);

    /**
     * 假设只有四个sheet，所以启动四个线程
     */
    private Executor executor = Executors.newFixedThreadPool(4);
    /**
     * 保存每个sheet计算出的银行流水的结果
     */
    private ConcurrentHashMap<String,Integer> sheetBankWateCount = new ConcurrentHashMap<String,Integer>();

    private void count(){
        for (int i = 0; i < 4; i++) {
            final int res = i +1;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    //计算当前sheet的银行流水，计算代码省略
                    sheetBankWateCount.put(Thread.currentThread().getName(),res);
                    System.out.println("sheet"+res+" finish count..");
                    //银行流水计算完成，插入一个屏障
                    try {
                        c.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                    System.out.println("sheet"+res+" barrier run..");
                }
            });
        }
    }

    @Override
    public void run() {
        int result = 0; // 总结果
        for(Map.Entry<String,Integer> sheet : sheetBankWateCount.entrySet()){
            result += sheet.getValue();
        }
        //将结果输出
        sheetBankWateCount.put("result",result);
        System.out.println("result:"+result);
    }

    public static void main(String[] args) {
        BankWateService bank = new BankWateService();
        bank.count();
    }
}
